package com.joekai.view_demo.heart_like;

import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;


public class DoubleClickListener implements View.OnTouchListener{
    private static int timeout=400;//双击间四百毫秒延时
    private int clickCount = 0;//记录连续点击次数
    private Handler handler;
    private DoubleClickCallBack doubleClickCallBack;

    public DoubleClickListener(DoubleClickCallBack doubleClickCallBack) {
        this.doubleClickCallBack = doubleClickCallBack;
        handler = new Handler();
    }
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            clickCount++;
            handler.postDelayed(() -> {
               if(clickCount>=2){
                   doubleClickCallBack.doubleClick(event);
                   clickCount=0;
                }
                handler.removeCallbacksAndMessages(null);
                //清空handler延时，并防内存泄漏
                clickCount = 0;//计数清零
            },timeout);//延时timeout后执行run方法中的代码
        }
        return false;//让点击事件继续传播，方便再给View添加其他事件监听
    }
}
